


var EXPORTED_SYMBOLS = ["RequestWatcher"];


let RequestWatcher = (function() {
    "use strict";
    const Cu = Components.utils;
    const Ci = Components.interfaces;
    const Cc = Components.classes;
    function require(url) {
        let scope = {};
        Cu.import(url, scope);
        return scope;
    }
    let {Prefs} = require("chrome://jsm/content/Preferences.js");
    let {Services} = require("resource://gre/modules/Services.jsm");
    

    return {
        broadcastMessage(topic, data) {
            Services.ppmm.broadcastAsyncMessage("imacros:"+topic, data);
        },

        receiveMessage(msg) {
            if (msg.name != "imacros:run-macro")
                return;
            let win = Services.wm.getMostRecentWindow("navigator:browser");
            win.iMacros.runMacro(msg.data).then(
                () => this.broadcastMessage("run-macro-completed")
            );
        },

        init() {
            this.loadList();
            Services.ppmm.addMessageListener("imacros:run-macro", this);
        },
        
        terminate() {
            Services.ppmm.removeMessageListener("imacros:run-macro", this);
            this.broadcastMessage("terminate");
        },

        
        enableImageFilter() {
            this.broadcastMessage("filter-on");
        },

        disableImageFilter() {
            this.broadcastMessage("filter-off");
        },
        

        listIsLoaded: false,
        whiteList: new Map(),

        
        addSite(site) {
            this.whiteList.set(site, true);
            this.saveList();
            this.broadcastMessage("update-whitelist", Prefs.sitesWhiteList);
        },

        
        blockSite(site) {
            this.whiteList.set(site, false);
            this.saveList();
            this.broadcastMessage("update-whitelist", Prefs.sitesWhiteList);
        },

        
        removeSite(site) {
            this.whiteList.delete(site);
            this.saveList();
            this.broadcastMessage("update-whitelist", Prefs.sitesWhiteList);
        },


        
        enumerateSites() {
            return Array.from(this.whiteList.entries())
                .map(arr => { return {site: arr[0], blocked: !arr[1]}; });
        },

        loadList() {
            let list = Prefs.sitesWhiteList;
            this.broadcastMessage("update-whitelist", list);
            this.whiteList.clear();
            for (let site in list)
                this.whiteList.set(site, list[site]);
            this.listIsLoaded = true;
        },


        saveList() {
            let obj = {};
            for (let entry of this.whiteList.entries())
                obj[entry[0]] = entry[1];
            Prefs.sitesWhiteList = obj;
        },

    };

})();
